<?php
/**
 *  💡 免责声明：本软件不得用于商业用途，仅做学习交流
 *  ⚠️ 权利声明：本软件由版权人提供产品技术支持
 *  📅 项目编号：NX2025-0135
 */
namespace App\Service\User;

use App\Models\PointSetting;
use App\Models\SinglePool;
use App\Models\SinglePoolTransaction;
use App\Service\BaseService;

class SinglePoolService extends BaseService
{
    /**
     * 充值
     * @param mixed $user_id
     * @param mixed $amount
     * @param mixed $describe
     * @param mixed $is_refund
     * @param mixed $transaction_type
     * @return false|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model|void
     */
    public function recharge($user_id, $amount)
    {
        if ($amount < 0) {
            return false;
        }
        $describe = '增加分红积分';
        $account = SinglePool::query()->firstOrCreate(
            ['user_id' => $user_id]
        );

        $account->balance += $amount;
        $account->save();
        $this->transactionHistory($user_id, $amount, $account->balance, 1, $describe);
        return $account;
    }

    /**
     * 消费.
     *
     * @param mixed $user_id
     * @param mixed $amount
     * @param mixed $describe
     * @param mixed $transaction_type
     * @return false|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model|void
     */
    public function consumption($user_id, $amount,$describe='系统分红')
    {
        $account = SinglePool::query()->firstOrCreate(
            ['user_id' => $user_id]
        );
        if ($account->balance - $amount < 0) {
            return false;
        }

        $account->balance -= $amount;
        $account->released_amount += $amount;
        $account->save();
        $this->transactionHistory($user_id, $amount, $account->balance, 2, $describe);
        return $account;
    }

    public function SingleAutoDividends()
    {
        //取出比例
        $pointSetting = PointSetting::query()->first();
        if ($pointSetting->on_group == 1) {
            $group_pool_price_bonus = $pointSetting->group_pool_price_bonus;
            $bouns = $this->generateRandomNumber($group_pool_price_bonus[0], $group_pool_price_bonus[1], 4);
            $reward_account = RewardAccountService::make();
            $point_account = PointAccountServices::make();
            SinglePool::query()
                ->where('balance', '>', 0)
                ->chunkById(500, function ($chunks) use ($bouns, $reward_account,$point_account) {
                    $describe = '分红积分转换';

                    $chunks->each(function ($item) use ($bouns, $describe, $reward_account,$point_account) {
                        $amount = bcmul($item->balance, $bouns, 2);
                        $item->decrement('balance', $amount);
                        $item->increment('released_amount', $amount);
                        $this->transactionHistory(
                            $item->user_id,
                            $amount,
                            $item->balance, // 计算新余额
                            2,
                            $describe
                        );
                        $res = $point_account->consumption($item->user_id, $amount,'分红积分转换:'.$amount);
                        if ( $res){
                            $reward_account->recharge($item->user_id, $amount, 6, '分红积分转换 奖励:'.$amount);
                        }
                    });
                }, 'id');
        }
    }

    protected function generateRandomNumber($min, $max, $precision = 0)
    {
        $factor = pow(10, $precision);
        $random = mt_rand($min * $factor, $max * $factor);
        return $random / $factor;
    }

    private function transactionHistory($user_id, $amount, $balance, $change_type, string $describe)
    {
        SinglePoolTransaction::query()->create([
            'user_id' => $user_id,
            'amount' => $amount,
            'balance' => $balance,
            'change_type' => $change_type,
            'describe' => $describe,
        ]);
    }
}
